package com.m2bshop.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.m2bshop.shop.common.imgUtils;
import com.m2bshop.shop.pojo.*;
import com.m2bshop.shop.pojo.Result.Result;
import com.m2bshop.shop.service.BMCService.BMCgoodsService;
import com.m2bshop.shop.service.BMCService.GoodcategoryService;
import com.m2bshop.shop.service.BMCService.GoodimgService;
import com.m2bshop.shop.service.BrandService;
import com.m2bshop.shop.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zhangyu
 * @create 2022/6/13 10:34
 */
@Controller
@RequestMapping("/BMC")
public class BMCgoodsController {

    @Autowired
    private BMCgoodsService bmCgoodsService;
    @Autowired
    private GoodimgService goodimgService;
    @Autowired
    private GoodcategoryService goodcategoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CompanyService companyService;
    //增加商品
    @RequestMapping("/add")
    @ResponseBody
    public Result addgoods(BMCgoods goods){
        int addgood = bmCgoodsService.addgood(goods);
        return Result.ok(addgood);
    }
    //获取所有品牌信息
    @RequestMapping("/getbrand")
    @ResponseBody
    public Result selectbrand(HttpSession session){
        String mvoId = session.getAttribute("username").toString();
        Company com = companyService.findComByMvoId(mvoId);
        List<Brand> brand = brandService.findBrandByComId(com.getCompanyId());
        return Result.ok(brand);
    }

    //更新商品
    @RequestMapping("/update")
    @ResponseBody
    public Result updategoods(BMCgoods goods){
        int updategood = bmCgoodsService.updategood(goods);
        return Result.ok(updategood);
    }
    //删除商品
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Result deletegoods(@PathVariable("id") int id){
        QueryWrapper<good_imgs> qg = new QueryWrapper<>();
        QueryWrapper<good_category> qgc = new QueryWrapper<>();
        qg.eq("goodid",id);
        qgc.eq("goodid",id);
        goodimgService.remove(qg);
        goodcategoryService.remove(qgc);
        int deletegood = bmCgoodsService.deletegood(id);
        return Result.ok(deletegood);
    }
    //查询所有商品
    @RequestMapping("/queryAll")
    @ResponseBody
    public Result queryAllgoods(){
        List<BMCgoods> bmCgoods = bmCgoodsService.queryAll();
        return Result.ok(bmCgoods);
    }
    //查询商品信息根据id
    @RequestMapping("/queryById")
    public Result queryByIdgoods(){
        return Result.ok();
    }
    //商品录入界面分页查询+关键字
    @RequestMapping("/queryPage/{page}/{pagenum}/{keyword}")
    @ResponseBody
    public Result queryPages(@PathVariable("page") int page, @PathVariable("pagenum") int pagenum
            , @PathVariable("keyword") String keyword,HttpSession session){
        String mvoId = session.getAttribute("username").toString();
        Company com = companyService.findComByMvoId(mvoId);
        QueryWrapper<BMCgoods> qw = new QueryWrapper();
        if(com!=null){
            List<Brand> brands = brandService.findBrandByComId(com.getCompanyId());
            if(brands.size() > 1 ) {
                for (int i = 0; i < brands.size(); i++) {
                    if (i == 0) {
                        qw.eq("id", brands.get(i).getBrandId());
                    } else {
                        qw.or().eq("id", brands.get(i).getBrandId());
                    }
                }
            }
        }else{
            Map<String,Object> ms = new HashMap<>();
            return Result.fail(ms);
        }
        if(!keyword.equals("''")){
            qw.like("name",keyword);
        }
        Page<BMCgoods> Page = new Page<>(page,pagenum);
        IPage<BMCgoods> ipgae = bmCgoodsService.page(Page,qw);
        List<BMCgoods> lb = ipgae.getRecords();
        Map<String,Object> ms = new HashMap<>();
        ms.put("total",ipgae.getTotal());
        ms.put("data",lb);
        return Result.ok(ms);
    }
    //商品主图分类分页查询+关键字
    @RequestMapping("/queryPageMain/{page}/{pagenum}/{keyword}")
    @ResponseBody
    public Result queryPageMain(@PathVariable("page") int page, @PathVariable("pagenum") int pagenum
            , @PathVariable("keyword") String keyword,HttpSession session){
        String mvoId = session.getAttribute("username").toString();
        Company com = companyService.findComByMvoId(mvoId);
        QueryWrapper<BMCgoods> qw = new QueryWrapper();
        if(com!=null){
            List<Brand> brands = brandService.findBrandByComId(com.getCompanyId());
            if(brands.size() > 1 ) {
                for (int i = 0; i < brands.size(); i++) {
                    if (i == 0) {
                        qw.eq("id", brands.get(i).getBrandId());
                    } else {
                        qw.or().eq("id", brands.get(i).getBrandId());
                    }
                }
            }
        }else {
            Map<String,Object> ms = new HashMap<>();
            return Result.fail(ms);
        }


        if(!keyword.equals("''")){
            qw.like("name",keyword);
        }
        Page<BMCgoods> Page = new Page<>(page,pagenum);
        IPage<BMCgoods> ipgae = bmCgoodsService.page(Page,qw);
        List<BMCgoods> lb = ipgae.getRecords();
        for(int i=0;i<lb.size();i++){
            BMCgoods bmCgoods = bmCgoodsService.queryById(lb.get(i).getId());
            lb.set(i,bmCgoods);
        }
        Map<String,Object> ms = new HashMap<>();
        ms.put("total",ipgae.getTotal());
        ms.put("data",lb);

        return Result.ok(ms);
    }
    //图片,商品分类修改
    @RequestMapping("/mainpic")
    @ResponseBody
    public Result AddPictures(MultipartFile[] files,int id,String category) throws IOException {
        imgUtils util = new imgUtils();
        int i = 1;
        QueryWrapper<good_imgs> qw = new QueryWrapper<good_imgs>();
        qw.eq("goodid",id);
        List<good_imgs> list = goodimgService.list(qw);
        if(list.size()>0){
            for (good_imgs g:list) {
                QueryWrapper<good_imgs> qs = new QueryWrapper<good_imgs>();
                qs.eq("id",g.getId());
                g.setSeq(i);
                goodimgService.update(g,qs);
                i++;
            }
        }
        if(files!=null) {
            for (MultipartFile f : files) {
                //图片保存
                String url = util.uploadImg(f, "实训");
                good_imgs gi = new good_imgs();
                gi.setGoodid(id);
                gi.setUrl(url);
                gi.setSeq(i);
                goodimgService.save(gi);
                i++;
            }
        }
        //种类保存
        QueryWrapper<good_category> qtw = new QueryWrapper<good_category>();
        qtw.eq("goodid",id);
        good_category one = goodcategoryService.getOne(qtw);
        if(one==null) {
            good_category gca = new good_category();
            gca.setCategoryname(category);
            gca.setGoodid(id);
            goodcategoryService.save(gca);
        }else{
            one.setCategoryname(category);
            goodcategoryService.update(one,qtw);
        }

        return Result.ok("保存成功");
    }

    @RequestMapping("/deleteImg/{id}")
    @ResponseBody
    public Result deleteImg(@PathVariable("id") int id){
        QueryWrapper<good_imgs> qg = new QueryWrapper<>();
        qg.eq("id",id);
        boolean remove = goodimgService.remove(qg);
        return Result.ok(remove);
    }

    @RequestMapping("/WebImg")
    @ResponseBody
    public void ShowImg(String path, HttpServletResponse response) {
        FileInputStream fis = null;
        OutputStream os = null;
        String filepath = path; //path是你服务器上图片的绝对路径
        URLDecoder.decode(filepath);
        File file = new File(filepath);
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                long size = file.length();
                byte[] temp = new byte[(int) size];
                fis.read(temp, 0, (int) size);
                fis.close();
                byte[] data = temp;
                response.setContentType("image/png");
                os = response.getOutputStream();
                os.write(data);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/test")
    @ResponseBody
    public Result Test() throws IOException {
        File directory = new File("");//参数为空
        String courseFile = directory.getCanonicalPath() ;
        return Result.ok();
    }
}
